package cn.xiaobai.core.handler;

import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 方法请求处理器
 *
 * @Author yangdaji
 * @Date 2023/12/10
 * @PackageName cn.xiaobai.core.handler
 * @ClassName MethodRequestHandler
 */
@Component
public class MethodRequestHandler {

    private Map<Object, List<Method>> beanMethodMap = new ConcurrentHashMap<>();

    public void addMethod(Object bean, Method... method) {
        beanMethodMap.put(bean, new ArrayList<>(List.of(method)));
    }

    public void invoke(Object target, String methodName, Object... args) {
        List<Method> methods = beanMethodMap.get(target);
        methods.stream()
                .filter(method -> method.getName().equals(methodName))
                .findAny().ifPresent(targetMethod -> ReflectionUtils.invokeMethod(targetMethod, target, args));
    }

}
